interface ChatMessage {
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp: number;
}

class AIAssistant {
    private electron = require('electron');
    private messages: ChatMessage[] = [];
    private isMinimized: boolean = false;
    private isDragging: boolean = false;
    private isResizing: boolean = false;
    private dragOffset: { x: number; y: number } = { x: 0, y: 0 };
    
    // DOM 元素
    private aiHeader!: HTMLElement;
    private aiChatContainer!: HTMLElement;
    private aiMessages!: HTMLElement;
    private aiInput!: HTMLTextAreaElement;
    private sendBtn!: HTMLButtonElement;
    private minimizeBtn!: HTMLButtonElement;
    private maximizeBtn!: HTMLButtonElement;
    private closeBtn!: HTMLButtonElement;
    private settingsBtn!: HTMLButtonElement;
    private resizeHandle!: HTMLElement;
    private noMessages!: HTMLElement;

    constructor() {
        this.initializeElements();
        this.setupEventListeners();
        this.setupTheme();
        this.autoResizeTextarea();
        
        // 发送就绪信号
        this.electron.ipcRenderer.send('ai-assistant-ready');
        
        console.log('AI助手初始化完成');
    }

    private initializeElements(): void {
        this.aiHeader = document.getElementById('aiHeader') as HTMLElement;
        this.aiChatContainer = document.getElementById('aiChatContainer') as HTMLElement;
        this.aiMessages = document.getElementById('aiMessages') as HTMLElement;
        this.aiInput = document.getElementById('aiInput') as HTMLTextAreaElement;
        this.sendBtn = document.getElementById('sendBtn') as HTMLButtonElement;
        this.minimizeBtn = document.getElementById('minimizeBtn') as HTMLButtonElement;
        this.maximizeBtn = document.getElementById('maximizeBtn') as HTMLButtonElement;
        this.closeBtn = document.getElementById('closeBtn') as HTMLButtonElement;
        this.settingsBtn = document.getElementById('settingsBtn') as HTMLButtonElement;
        this.resizeHandle = document.getElementById('resizeHandle') as HTMLElement;
        this.noMessages = document.getElementById('noMessages') as HTMLElement;
    }

    private setupEventListeners(): void {
        // 发送消息
        this.sendBtn.addEventListener('click', () => this.sendMessage());
        this.aiInput.addEventListener('keydown', (e: KeyboardEvent) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // 窗口控制
        this.minimizeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleMinimize();
        });
        this.maximizeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleMaximize();
        });
        this.closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.closeWindow();
        });
        this.settingsBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.openSettings();
        });

        // 拖拽功能
        this.aiHeader.addEventListener('mousedown', (e: MouseEvent) => this.startDrag(e));
        document.addEventListener('mousemove', (e: MouseEvent) => this.handleDrag(e));
        document.addEventListener('mouseup', () => this.stopDrag());

        // 调整大小功能
        this.resizeHandle.addEventListener('mousedown', (e: MouseEvent) => this.startResize(e));
        document.addEventListener('mousemove', (e: MouseEvent) => this.handleResize(e));
        document.addEventListener('mouseup', () => this.stopResize());

        // IPC 消息监听
        this.setupIpcListeners();

        // 自适应文本框高度
        this.aiInput.addEventListener('input', () => this.autoResizeTextarea());
    }

    private setupIpcListeners(): void {
        // 接收AI回复
        this.electron.ipcRenderer.on('ai-response', (event: Electron.IpcRendererEvent, response: string) => {
            this.addMessage('assistant', response);
            this.enableInput();
        });

        // 接收AI错误
        this.electron.ipcRenderer.on('ai-error', (event: Electron.IpcRendererEvent, error: string) => {
            this.addMessage('assistant', `抱歉，发生了错误：${error}`);
            this.enableInput();
        });

        // 接收当前选中文本（用于上下文）
        this.electron.ipcRenderer.on('set-selected-text', (event: Electron.IpcRendererEvent, text: string) => {
            if (text && text.trim()) {
                this.addContextInfo(`选中文本：${text}`);
            }
        });

        // 接收当前翻译项目上下文
        this.electron.ipcRenderer.on('set-translation-context', (event: Electron.IpcRendererEvent, context: any) => {
            if (context) {
                this.addContextInfo(`当前片段：${context.source} → ${context.target}`);
            }
        });

        // 接收AI设置更新
        this.electron.ipcRenderer.on('ai-settings-updated', (event: Electron.IpcRendererEvent, settings: any) => {
            this.updateProviderDisplay(settings);
        });

        // 主题设置
        this.electron.ipcRenderer.on('set-theme', (event: Electron.IpcRendererEvent, theme: string) => {
            const themeLink = document.getElementById('theme') as HTMLLinkElement;
            if (themeLink) {
                themeLink.href = theme;
            }
        });
    }

    private setupTheme(): void {
        // 监听主题变化
        this.electron.ipcRenderer.on('set-theme', (event: Electron.IpcRendererEvent, theme: string) => {
            const themeLink = document.getElementById('theme') as HTMLLinkElement;
            if (themeLink) {
                themeLink.href = theme;
            }
        });
        
        // 请求当前主题
        this.electron.ipcRenderer.send('get-theme');
    }

    private sendMessage(): void {
        const content = this.aiInput.value.trim();
        if (!content) return;

        // 添加用户消息
        this.addMessage('user', content);
        this.aiInput.value = '';
        this.autoResizeTextarea();
        this.disableInput();

        // 显示thinking状态
        this.showThinking();

        // 构建消息历史（支持多轮对话）
        const conversationHistory = this.messages.map(msg => ({
            role: msg.role,
            content: msg.content
        }));

        // 发送到主进程
        this.electron.ipcRenderer.send('ai-chat', conversationHistory);
    }

    private addMessage(role: 'user' | 'assistant', content: string): void {
        const message: ChatMessage = {
            role,
            content,
            timestamp: Date.now()
        };

        this.messages.push(message);
        this.renderMessage(message);
        this.scrollToBottom();
        this.updateNoMessagesVisibility();
    }

    private renderMessage(message: ChatMessage): void {
        // 移除thinking状态
        this.removeThinking();

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${message.role}`;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = message.content;

        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime(message.timestamp);

        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timeDiv);
        this.aiMessages.appendChild(messageDiv);
    }

    private addContextInfo(info: string): void {
        const contextDiv = document.createElement('div');
        contextDiv.className = 'context-info';
        contextDiv.textContent = info;
        this.aiMessages.appendChild(contextDiv);
        this.scrollToBottom();
    }

    private showThinking(): void {
        this.removeThinking(); // 确保只有一个thinking状态
        
        const thinkingDiv = document.createElement('div');
        thinkingDiv.className = 'thinking';
        thinkingDiv.id = 'thinking-indicator';
        
        const dotsDiv = document.createElement('div');
        dotsDiv.className = 'thinking-dots';
        
        for (let i = 0; i < 3; i++) {
            const dot = document.createElement('div');
            dot.className = 'thinking-dot';
            dotsDiv.appendChild(dot);
        }
        
        thinkingDiv.appendChild(dotsDiv);
        this.aiMessages.appendChild(thinkingDiv);
        this.scrollToBottom();
    }

    private removeThinking(): void {
        const thinking = document.getElementById('thinking-indicator');
        if (thinking) {
            thinking.remove();
        }
    }

    private scrollToBottom(): void {
        this.aiMessages.scrollTop = this.aiMessages.scrollHeight;
    }

    private updateNoMessagesVisibility(): void {
        this.noMessages.style.display = this.messages.length > 0 ? 'none' : 'flex';
    }

    private formatTime(timestamp: number): string {
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    }

    private disableInput(): void {
        this.aiInput.disabled = true;
        this.sendBtn.disabled = true;
    }

    private enableInput(): void {
        this.aiInput.disabled = false;
        this.sendBtn.disabled = false;
        this.aiInput.focus();
    }

    private autoResizeTextarea(): void {
        this.aiInput.style.height = 'auto';
        const scrollHeight = this.aiInput.scrollHeight;
        const maxHeight = 120; // 对应CSS中的max-height
        this.aiInput.style.height = Math.min(scrollHeight, maxHeight) + 'px';
    }

    // 窗口控制功能
    private toggleMinimize(): void {
        this.isMinimized = !this.isMinimized;
        document.body.classList.toggle('minimized', this.isMinimized);
        
        // 通知主进程调整窗口大小
        this.electron.ipcRenderer.send('ai-assistant-minimize-toggle', this.isMinimized);
        
        console.log('AI助手最小化状态:', this.isMinimized);
    }

    private toggleMaximize(): void {
        this.electron.ipcRenderer.send('ai-assistant-maximize-toggle');
    }

    private closeWindow(): void {
        this.electron.ipcRenderer.send('ai-assistant-close');
    }

    private openSettings(): void {
        this.electron.ipcRenderer.send('ai-assistant-open-settings');
    }

    // 拖拽功能
    private startDrag(e: MouseEvent): void {
        // 检查是否点击的是按钮或控制区域
        const target = e.target as HTMLElement;
        if (target.tagName === 'BUTTON' || 
            target.closest('button') || 
            target.closest('.ai-controls') ||
            target.classList.contains('control-btn')) {
            return; // 如果点击的是按钮或控制区域，不启动拖拽
        }

        this.isDragging = true;
        this.dragOffset.x = e.clientX;
        this.dragOffset.y = e.clientY;
        
        document.body.style.cursor = 'move';
        e.preventDefault();
    }

    private handleDrag(e: MouseEvent): void {
        if (!this.isDragging) return;

        const deltaX = e.clientX - this.dragOffset.x;
        const deltaY = e.clientY - this.dragOffset.y;
        
        // 通知主进程移动窗口
        this.electron.ipcRenderer.send('ai-assistant-move', { deltaX, deltaY });
        
        this.dragOffset.x = e.clientX;
        this.dragOffset.y = e.clientY;
    }

    private stopDrag(): void {
        if (this.isDragging) {
            this.isDragging = false;
            document.body.style.cursor = 'default';
        }
    }

    // 调整大小功能
    private startResize(e: MouseEvent): void {
        this.isResizing = true;
        this.dragOffset.x = e.clientX;
        this.dragOffset.y = e.clientY;
        
        document.body.style.cursor = 'nw-resize';
        e.preventDefault();
        e.stopPropagation();
    }

    private handleResize(e: MouseEvent): void {
        if (!this.isResizing) return;

        const deltaX = e.clientX - this.dragOffset.x;
        const deltaY = e.clientY - this.dragOffset.y;
        
        // 通知主进程调整窗口大小
        this.electron.ipcRenderer.send('ai-assistant-resize', { deltaX, deltaY });
        
        this.dragOffset.x = e.clientX;
        this.dragOffset.y = e.clientY;
    }

    private stopResize(): void {
        if (this.isResizing) {
            this.isResizing = false;
            document.body.style.cursor = 'default';
        }
    }

    // 公共方法
    public clearChat(): void {
        this.messages = [];
        this.aiMessages.innerHTML = '';
        this.aiMessages.appendChild(this.noMessages);
        this.updateNoMessagesVisibility();
    }

    public addWelcomeMessage(): void {
        this.addMessage('assistant', '你好！我是DeepSeek AI助手，可以帮助你进行翻译、答疑和文本处理。有什么我可以帮助你的吗？');
    }

    private updateProviderDisplay(settings: any): void {
        // 更新标题显示当前的AI提供商
        const titleElement = document.querySelector('.ai-title') as HTMLElement;
        if (titleElement) {
            if (settings.provider === 'anythingllm' && settings.anythingllm?.selectedWorkspace) {
                titleElement.textContent = `AnythingLLM - ${settings.anythingllm.selectedWorkspace.name}`;
            } else {
                titleElement.textContent = 'DeepSeek AI 助手';
            }
        }

        // 如果切换到AnythingLLM，显示欢迎消息
        if (settings.provider === 'anythingllm' && settings.anythingllm?.selectedWorkspace) {
            this.addMessage('assistant', `已连接到AnythingLLM工作区"${settings.anythingllm.selectedWorkspace.name}"。我可以基于该工作区的知识库为您提供帮助。`);
        } else if (settings.provider === 'deepseek') {
            this.addMessage('assistant', '已切换到DeepSeek AI模式。我可以帮助您进行翻译、答疑和文本处理。');
        }
    }

    public insertSelectedText(): void {
        // 请求主进程获取当前选中的文本
        this.electron.ipcRenderer.send('get-selected-text');
    }

    public getTranslationContext(): void {
        // 请求主进程获取当前翻译上下文
        this.electron.ipcRenderer.send('get-translation-context');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new AIAssistant();
}); 